package shark.picture.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import shark.picture.annotation.AuthCheck;
import shark.picture.common.BaseResponse;
import shark.picture.common.DeleteRequest;
import shark.picture.common.ResultUtils;
import shark.picture.data.constant.UserConstant;
import shark.picture.data.dto.uer.*;
import shark.picture.data.entity.User;
import shark.picture.exception.BusinessException;
import shark.picture.exception.ErrorCode;
import shark.picture.exception.ThrowUtils;
import shark.picture.service.UserService;
import shark.picture.data.vo.user.LoginUserVO;
import shark.picture.data.vo.user.UserVO;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jianxin.wei
 * @description 用户
 * @date 2025/2/10 17:29
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    @GetMapping("/get/login")
    @ApiOperation(value = "获取当前登录用户信息")
    public BaseResponse<User> getLoginUser(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        User userVO = userService.getLoginUser(request);
        return ResultUtils.success(userVO);
    }

    @GetMapping("/get/logout")
    @ApiOperation(value = "用户登出")
    public BaseResponse<Boolean> getLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }


    @PostMapping("/add")
    @ApiOperation(value = "创建用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        Long userId = userService.addUser(userAddRequest);
        return ResultUtils.success(userId);
    }

    @GetMapping("/get")
    @ApiOperation(value = "根据 id 获取用户（仅管理员）")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    @GetMapping("/get/vo")
    @ApiOperation(value = "根据 id 获取包装类")
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除用户（仅管理员）")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(deleteRequest.getId());
        ThrowUtils.throwIf("shark".equals(user.getUserName()), ErrorCode.OPERATION_ERROR);
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新用户（仅管理员）")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @PostMapping("/list/page/vo")
    @ApiOperation(value = "分页获取用户封装列表（仅管理员）")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

//    @PostMapping("Test")
//    public BaseResponse<Object> Test(HttpServletRequest request) throws UnsupportedEncodingException {
//        request.setCharacterEncoding("UTF-8");
//        String parameter = request.getParameter("param");
//        JSONObject object = JSONUtil.parseObj(parameter);
//        String ymd = object.getStr("YMD");
//        JSONArray dataList = object.getJSONArray("dataList");
//        for (int i = 0; i < dataList.size(); i++) {
//            JSONObject data = dataList.getJSONObject(i);
//            String sjMeterDataId = data.getStr("SJ_METER_DATA_ID");
//            String custNo = data.getStr("CUST_NO");
//            String meterId = data.getStr("METER_ID");
//            String assetNo = data.getStr("ASSET_NO");
//            String readType = data.getStr("READ_TYPE");
//            String sendTime = data.getStr("SEND_TIME");
//            Map<String, String> map = new HashMap<>();
//            for (int j = 1; j < 97; j++) {
//                String key = "SJ" + j;
//                if (j < 10) {
//                    key = "SJ0" + j;
//                }
//                map.put(key, data.getStr(key));
//            }
//            System.out.println();
////            Db.update("")
//        }
//
//
//        return ResultUtils.success("");
//    }

    public static boolean sql_inj(String str) {

        String inj_str = "'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+|,";
        List<String> split = StrUtil.split(inj_str, "|");
        for (String string : split) {
            if (str.contains(string)) {
                return true;
            }
        }

        return false;

    }


}
